package com.yj.suncity.user;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.yj.suncity.R;
import com.yj.suncity.area.ProvinceSelectActivity;
import com.yj.suncity.constant.ShareCon;
import com.yj.suncity.constant.URLCon;
import com.yj.suncity.user.bean.LoginBean;
import com.yj.suncity.utis.DialogUtils;
import com.yj.suncity.utis.HttpUtil;
import com.yj.suncity.utis.ProgressUtil;
import com.yj.suncity.utis.SharedPreferencesUtil;
import com.yj.suncity.utis.ToastUtil;
import com.yj.suncity.utis.UploadUtil;
import com.yj.suncity.utis.DialogUtils.ItemCall;
import com.yj.suncity.utis.DialogUtils.ReshActivity;
import com.yj.suncity.utis.UploadUtil.OnUploadProcessListener;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

public class RegistActivity2 extends Activity implements OnClickListener {
	private final int PIC_FROM_CAMERA = 1001;
	private final int PIC_FROM＿LOCALPHOTO = 1002;
	private static final int FAIL = 1;
	private static final int SUCCESS = 2;
	private static final int IO_EXCEPTION = 3;
	private static final int JSON_EXCEPTION = 4;
	private Context context;
	private int userType;// 1、个人；2、商户
	private TextView mTxt_title_name;
	private List<NameValuePair> pairs;
	private EditText mEdt_user_name, mEdt_user_pwd1, mEdt_user_pwd2,
			mEdt_recommen_phone;
	private TextView mTxt_user_address, mTxt_shop;
	private View mLay_rela_cate, mView_div;
	private String cityName;
	private String cityId;
	private String cateName;// 分类名称
	private String cateId;// 分类id
	private String phone;
	private String pwd;
	private ImageView mImg_user_head;
	private String uploadHead = "";
	private SharedPreferencesUtil preferencesUtil;
	private ProgressUtil progressUtil;
	private DisplayImageOptions options;
	private ImageLoader imageLoader = ImageLoader.getInstance();
	Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case FAIL:
				progressUtil.ShowProgress(context, false, false, "正在注册......");
				ToastUtil.ShowToast(context, "" + "" + (String) msg.obj);
				break;
			case SUCCESS:
				progressUtil.ShowProgress(context, false, false, "正在注册......");
				setShare((LoginBean) msg.obj);
				break;
			case IO_EXCEPTION:
				progressUtil.ShowProgress(context, false, false, "正在注册......");
				ToastUtil.ShowToast(context, "网络异常！");
				break;
			case JSON_EXCEPTION:
				progressUtil.ShowProgress(context, false, false, "正在注册......");
				ToastUtil.ShowToast(context, "数据解析异常！");
				break;
			default:
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_regist2);
		preferencesUtil = SharedPreferencesUtil.getInstance();
		userType = getIntent().getIntExtra("usertype", 0);
		phone = getIntent().getStringExtra("phone");
		pwd = getIntent().getStringExtra("pwd");
		context = this;
		pairs = new ArrayList<NameValuePair>();
		options = new DisplayImageOptions.Builder()
				.showStubImage(R.drawable.user_head)
				.showImageForEmptyUri(R.drawable.user_head)
				.showImageOnFail(R.drawable.user_head).cacheInMemory(true)
				.cacheOnDisc(true).bitmapConfig(Bitmap.Config.RGB_565) // 设置图片的解码类型
				.build();
		findView();
	}

	private void findView() {
		mImg_user_head = (ImageView) findViewById(R.id.img_user_head);
		mImg_user_head.setOnClickListener(this);
		mTxt_title_name = (TextView) findViewById(R.id.txt_title_name);
		mLay_rela_cate = findViewById(R.id.lay_rela_cate);
		mView_div = findViewById(R.id.view_div);

		if (userType == 1) {
			mTxt_title_name.setText("个人注册(3/3)");
			mLay_rela_cate.setVisibility(View.GONE);
			mView_div.setVisibility(View.GONE);
		} else if (userType == 2) {
			mTxt_title_name.setText("商户注册(3/3)");
			mLay_rela_cate.setVisibility(View.VISIBLE);
			mView_div.setVisibility(View.VISIBLE);
		}

		mEdt_user_name = (EditText) findViewById(R.id.edt_user_name);
		mEdt_recommen_phone = (EditText) findViewById(R.id.edt_tuijian_phone);
		mEdt_user_pwd1 = (EditText) findViewById(R.id.edt_user_pwd1);
		mEdt_user_pwd2 = (EditText) findViewById(R.id.edt_user_pwd2);

		mTxt_user_address = (TextView) findViewById(R.id.txt_user_address);
		mTxt_user_address.setOnClickListener(this);

		mTxt_shop = (TextView) findViewById(R.id.txt_shop);// 商家商品分类
		mTxt_shop.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btnHeadBack:
			this.finish();
			break;
		case R.id.img_user_head:// 点击上传头像
			popPhotoView();
			break;
		case R.id.txt_user_address:
			startActivityForResult(new Intent(this,
					ProvinceSelectActivity.class), 101);
			break;
		case R.id.txt_shop:// 行业
			startActivityForResult(new Intent(this, ShopCateActivity.class),
					102);
			break;
		case R.id.btn_regist:
			String userName = mEdt_user_name.getText().toString().trim();
			String recommenPhone = mEdt_recommen_phone.getText().toString()
					.trim();

			if (uploadHead.equals("")) {
				ToastUtil.ShowToast(context, "请选择头像！");
				return;
			}
			
			if (userName.equals("")) {
				ToastUtil.ShowToast(context, "请输入用户名！");
				return;
			}

			if (userType == 2 && cateId == null) {
				ToastUtil.ShowToast(context, "请选择行业！");
				return;
			}

			if (cityId == null) {
				ToastUtil.ShowToast(context, "请选择地址！");
				return;
			}
			// 修改
			progressUtil = new ProgressUtil();
			progressUtil.ShowProgress(context, true, false, "正在注册......");

			if (uploadHead.equals("")) {
				Regist(userName, pwd, recommenPhone);
			} else {
				UpLoadHead(userName, pwd, recommenPhone);// 首先上传头像
			}
		default:
			break;
		}
	}

	private void UpLoadHead(final String userName, final String userPwd,
			final String recommenPhone) {
		Map<String, String> param = new LinkedHashMap<String, String>();
		List<String> filePaths = new ArrayList<String>();
		filePaths.add(uploadHead);
		param.put("action", "uploads");
		UploadUtil uploadUtil = new UploadUtil();
		uploadUtil.uploadFile(context, filePaths, "txtimg", URLCon.图片上传, param,
				new OnUploadProcessListener() {
					@Override
					public void UploadResule(String result) {
						Log.d("", "result===" + result);
						// {"success":"1","msg":"ä¸ä¼ æå","data":[{"url":
						// "/upload/201504/15/201504151021483780.jpg"}]}
						try {
							JSONObject jsonObject = new JSONObject(result);
							if (jsonObject.optString("success").equals("1")) {
								JSONArray array = jsonObject
										.optJSONArray("data");
								JSONObject item = array.optJSONObject(0);
								uploadHead = item.optString("url");
								Regist(userName, userPwd, recommenPhone);
							} else {
								Message message = new Message();
								message.what = FAIL;
								message.obj = jsonObject.optString("msg");
								handler.sendMessage(message);
							}
						} catch (JSONException e) {
							Message message = new Message();
							message.what = JSON_EXCEPTION;
							handler.sendMessage(message);
							e.printStackTrace();
						}
					}
				});

	}

	// 设置注册参数
	private void setPairs(String userName, String userPwd, String recommenPhone) {
		pairs.clear();
		pairs.add(new BasicNameValuePair("action", "register"));
		pairs.add(new BasicNameValuePair("mobile", phone));
		pairs.add(new BasicNameValuePair("password", userPwd));
		pairs.add(new BasicNameValuePair("usertype", String.valueOf(userType)));
		pairs.add(new BasicNameValuePair("username", userName));
		pairs.add(new BasicNameValuePair("recommenmobile", recommenPhone));
		pairs.add(new BasicNameValuePair("districtid", cityId));
		pairs.add(new BasicNameValuePair("districtname", cityName));
		pairs.add(new BasicNameValuePair("birthday", "2010-12-26"));
		pairs.add(new BasicNameValuePair("photo", uploadHead));
		// 商户传
		if (userType == 2) {
			pairs.add(new BasicNameValuePair("tradename", cateName));
			pairs.add(new BasicNameValuePair("tradeid", cateId));
		}

	}

	private void Regist(String userName, String userPwd, String recommenPhone) {
		setPairs(userName, userPwd, recommenPhone);
		final String path = URLCon.用户;
		Thread thread = new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					String json = HttpUtil.HttpClientdoPost(path, pairs);
					if (json != null) {
						JSONObject jsonObject = new JSONObject(json);
						LoginBean loginBean = new LoginBean(jsonObject);
						Message message = new Message();
						message.obj = loginBean;
						message.what = SUCCESS;
						handler.sendMessage(message);
					}
				} catch (IOException e) {
					Message message = new Message();
					message.what = IO_EXCEPTION;
					handler.sendMessage(message);
					e.printStackTrace();
				} catch (JSONException e) {
					Message message = new Message();
					message.what = JSON_EXCEPTION;
					handler.sendMessage(message);
					e.printStackTrace();
				}

			}
		});
		thread.start();
		thread = null;
	}

	private void setShare(LoginBean loginBean) {
		if (loginBean.getSuccess().equals("1")) {
			preferencesUtil.putBoolean(context, ShareCon.USERFILE,
					ShareCon.ISLOGIN, true);
			preferencesUtil.putString(context, ShareCon.USERFILE,
					ShareCon.USERID, loginBean.getId());
			preferencesUtil.putString(context, ShareCon.USERFILE,
					ShareCon.USERNAME, loginBean.getUsername());
			preferencesUtil.putString(context, ShareCon.USERFILE,
					ShareCon.USERPHONE, loginBean.getTelphone());
			preferencesUtil.putString(context, ShareCon.USERFILE,
					ShareCon.USERLOGO, loginBean.getHead_photo());
			preferencesUtil.putString(context, ShareCon.USERFILE,
					ShareCon.USERINTEGRAL, loginBean.getPositionid());
			if (loginBean.getUser_type().equals("2")) {// 商户
				preferencesUtil.putBoolean(context, ShareCon.USERFILE,
						ShareCon.USERTYPE, true);
				preferencesUtil.putString(context, ShareCon.USERFILE,
						ShareCon.SHOPID, loginBean.getEntid());
			} else {
				preferencesUtil.putBoolean(context, ShareCon.USERFILE,
						ShareCon.USERTYPE, false);
			}
			DialogUtils dialogUtils = DialogUtils.getInstance();
			dialogUtils.backDialog(context, "恭喜！您已注册成功！", false,
					new ReshActivity() {
						@Override
						public void reshActivity() {
							setResult(1);
							RegistActivity2.this.finish();
						}
					});
		} else {
			DialogUtils dialogUtils = DialogUtils.getInstance();
			dialogUtils.backDialog(context, "" + loginBean.getMsg(), false,
					null);
		}
	}

	private void popPhotoView() {
		DialogUtils dialogUtils = DialogUtils.getInstance();
		dialogUtils.SelectPicDialog(context, new ItemCall() {
			@Override
			public void onIndexCall(int index) {
				if (index == 0) {
					doHandlerPhoto(PIC_FROM_CAMERA);
				} else {
					doHandlerPhoto(PIC_FROM＿LOCALPHOTO);
				}
			}
		});
	}

	/**
	 * 根据不同方式选择图片设置ImageView
	 * 
	 * @param type
	 *            0-本地相册选择，非0为拍照
	 */
	private Uri photoUri;// 需要上传的头像

	private void doHandlerPhoto(int type) {
		try {
			// 保存裁剪后的图片文件
			File pictureFileDir = new File(
					Environment.getExternalStorageDirectory(), "/upload");
			if (!pictureFileDir.exists()) {
				pictureFileDir.mkdirs();
			} else {
				File[] files = pictureFileDir.listFiles();
				if (files != null) {
					for (File file : files) {
						file.delete();
					}
				}
			}
			File picFile = new File(pictureFileDir, getPhotoFileName());
			if (!picFile.exists()) {
				picFile.createNewFile();
			}
			photoUri = Uri.fromFile(picFile);
			// photoUri = picFile.toString();
			if (type == PIC_FROM＿LOCALPHOTO) {
				Intent intent = getCropImageIntent();
				startActivityForResult(intent, PIC_FROM＿LOCALPHOTO);
			} else {
				Intent cameraIntent = new Intent(
						MediaStore.ACTION_IMAGE_CAPTURE);
				cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
				startActivityForResult(cameraIntent, PIC_FROM_CAMERA);
			}

		} catch (Exception e) {
			Log.i("HandlerPicError", "处理图片出现错误");
		}
	}

	/**
	 * 调用本地图片剪辑程序
	 */
	public Intent getCropImageIntent() {
		Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
		intent.setType("image/*");
		setIntentParams(intent);
		return intent;
	}

	/**
	 * 启动相机裁剪程序
	 */
	private void cropImageUriByTakePhoto() {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(photoUri, "image/*");
		setIntentParams(intent);
		startActivityForResult(intent, PIC_FROM＿LOCALPHOTO);
	}

	/**
	 * 设置公用参数
	 */
	private void setIntentParams(Intent intent) {
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", 600);
		intent.putExtra("outputY", 600);
		intent.putExtra("noFaceDetection", true); // no face detection
		intent.putExtra("scale", true);
		intent.putExtra("return-data", false);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
		intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
	}

	/**
	 * 用时间戳生成照片名称
	 * 
	 * @return
	 */
	private String getPhotoFileName() {
		Date date = new Date(System.currentTimeMillis());
		SimpleDateFormat dateFormat = new SimpleDateFormat(
				"'IMG'yyyyMMddHHmmss");
		return dateFormat.format(date) + ".jpg";
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case PIC_FROM_CAMERA: // 拍照
			try {
				cropImageUriByTakePhoto();
			} catch (Exception e) {
				e.printStackTrace();
			}
			break;
		case PIC_FROM＿LOCALPHOTO:
			try {
				if (photoUri != null) {
					uploadHead = photoUri.toString().replace("file://", "");

					imageLoader.displayImage("file://" + uploadHead,
							mImg_user_head, options);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			break;
		}

		if (requestCode == 101 && resultCode == 101) {
			Log.d("",
					data.getStringExtra("allname") + "======="
							+ data.getStringExtra("countyname") + "======="
							+ data.getStringExtra("areaid"));
			cityId = data.getStringExtra("areaid");
			cityName = data.getStringExtra("allname");
			mTxt_user_address.setText(cityName);
		}
		if (requestCode == 102 && resultCode == 102) {
			Log.d("",
					data.getStringExtra("catename") + "======="
							+ data.getStringExtra("cateid"));
			cateId = data.getStringExtra("cateid");
			cateName = data.getStringExtra("catename");
			mTxt_shop.setText(cateName);
		}
	}

}
